<?php
/**
 * Short Description  
 *
 * Long Description 
 *
 * @category   
 * @package    
 * @subpackage 
 * @copyright 
 * @author     Sandeep Manne<sandeep.manne@costrategix.com>
 */

class Core_Image_Adapter_Imagemagic extends Core_Image_Adapter_Abstract
{
	protected $_requiredExtensions = Array("imagick");
	
	public function open($filename)
    {
        $this->_fileName = $filename;
        $this->getMimeType();
        $this->_getFileAttributes();
        $this->_imageHandler = new Imagick($filename);
    }
    
    public function save()
    {}
    
	public function display()
    {
        header("Content-type: ".$this->getMimeType());
        echo $this->_imageHandler;
    }
    
	public function checkAlpha($fileName)
    {
        return ((ord(file_get_contents($fileName, false, null, 25, 1)) & 6) & 4) == 4;
    }
    
    public function resize($frameWidth = null, $frameHeight = null)
    {
    	$this->_imageHandler->thumbnailImage($frameWidth, $frameHeight);
    	$this->refreshImageDimensions();
    	$this->optimizeImage();
    }
    
    public function rotate($angle)
    {
    	$this->_imageHandler->rotateImage(new ImagickPixel(), $angle);
    }
    
    public function watermark($watermarkImage, $positionX=0, $positionY=0, $watermarkImageOpacity=30, $repeat=false)
    {}
    
    public function crop($width=0, $height=0, $xCoordinate=0, $yCoordinate=0)
    {
        $this->_imageHandler->cropImage($width, $height, $xCoordinate, $yCoordinate);
        $this->refreshImageDimensions();
        $this->optimizeImage();
    }
    
	public function checkDependencies()
    {
        foreach( $this->_requiredExtensions as $value ) {
            if( !extension_loaded($value) ) {
                throw new Exception("Required PHP extension '{$value}' was not loaded.");
            }
        }
    }
    
   private function refreshImageDimensions()
   {
        $size = $this->_imageHandler->getImageGeometry(); 
    	$this->_imageSrcWidth  = $size['width']; 
        $this->_imageSrcHeight = $size['height']; 
   }
   
   function __destruct()
   {
        $this->_imageHandler->destroy();
   }
   
}